import React, { Component } from 'react';
import {
    Button, Form, Radio, Row, Input, Select, Col, message,Card,DatePicker
} from 'antd';
import { connect } from 'dva';
import InputText from '@/components/Input/index';
import Preview from './preview';
import styles from './index.less';
import router from 'umi/router';
import moment from 'moment';
const { TextArea } = Input;
const Option = Select.Option;
const { RangePicker} = DatePicker;
const RadioGroup = Radio.Group;

@connect(({global, marketing, loading}) => ({
    oemInfo: global.oemInfo,
    marketing,
    loading: loading.effects['marketing/AddCoupon'],
}))

class ReleaseCards extends Component {
    constructor() {
        super();
        this.state= {
            ConditionType: 'a',
            LimitCountValue: 'a',
            ConditionNum: '',
            WaiverAmountNum: '',
            ConditionDesable: true,
            LimitCountDesable: true,
            textName: '',
            dateString: ['',''],
            radio1: false,
            radio2: false
        }
    }
    componentWillMount() {
      window.Isoption = false;
    }

    componentDidMount() {
      window.Isoption = true;
        // this.findLevelList();
    }

  handleSubmit =(e) => {
    e.preventDefault();
    let { dispatch} = this.props;
    this.props.form.validateFieldsAndScroll({force: true}, (err, values) => {
        if(!err) {
            // return;
            dispatch({
                type: 'marketing/AddCoupon',
                payload: {
                    Name: values.Name,
                    TotalQty: values.TotalQty,
                    Condition: values.radio1==='a'? 0 :values.Condition, //门槛
                    WaiverAmount: values.WaiverAmount,
                    ValidStartTime: values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
                    ValidEndTime: values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
                    LimitCount: values.radio2==='a'? 0 :values.LimitCount, //次数
                    Description: values.Description,
                },
                callBack: {
                    success: res => {
                        if(res.Code ===0) {
                            message.success('保存成功');
                            router.replace({
                                pathname: `/${window.storeId}/marketing/coupon`,
                            });
                        }
                    },
                    error: res => {
                        message.error(res.Msg)
                    }
                }
            })
        }
    })}

   // 校验名
   checkName = (e) => {
    this.props.form.validateFields(['name'], { force: true });
  }

    // 修改名称
    onTextChange = (v) => {
        this.setState({ name: v.target.value });
        this.props.form.setFieldsValue({
            Name: v.target.value
        })
    }

    // 限制次数
    onChangeLimitCount =(e) => {
        this.setState({
            LimitCountValue: e.target.value,
          });
          if(e.target.value ==='b') {
            this.setState({
                radio2: true,
                LimitCountDesable: false
            })
        } else {
            this.setState({
                radio2: false,
                LimitCountDesable: true
            })
            this.props.form.setFieldsValue({
                LimitCount: ''
            })
        }
    }

    // 门槛
    onChangeConditionType =(e) => {
        const {ConditionNum, WaiverAmountNum,dateString} = this.state;
        this.setState({
            ConditionType: e.target.value
        })
        if(e.target.value ==='b') {
            this.setState({
                radio1: true,
                ConditionDesable: false
            })
        } else {
            this.setState({
                radio1: false,
                ConditionDesable: true
            })
            this.props.form.setFieldsValue({
                Condition: ''
            })
        }
        const d = `全部商品可用\r${e.target.value==='a'?'无使用门槛':'订单满'+`${ConditionNum}`+'元'}\r${WaiverAmountNum&&'减免'+`${WaiverAmountNum+'元'}`}\r${dateString[0]&&'有效时限:'+ `${dateString[0]}`+ '~'+`${dateString[1]}`}`;
        const dd = `全部商品可用\\r${e.target.value==='a'?'无使用门槛':'订单满'+`${ConditionNum}`+'元'}\\r${WaiverAmountNum&&'减免'+`${WaiverAmountNum+'元'}`}\\r${dateString[0]&&'有效时限:'+ `${dateString[0]}`+ '~'+`${dateString[1]}`}`;
        this.setState({
            Description: dd
        })
        this.props.form.setFieldsValue({
            Description: d,
        })
    }

    // `全部商品可用\r${e.target.value==='a'?'无使用门槛':'订单满'+`${ConditionNum}`+'元'}\r${WaiverAmountNum&&'减免'+`${WaiverAmountNum+'元'}`}\r${dateString[0]&&'有效时限:'+ `${dateString[0]}`+ '~'+`${dateString[1]}`}`

    // 满减额
    onChangeCondition =(e) => {
        const {ConditionType, WaiverAmountNum,dateString} = this.state;
        this.setState({
            ConditionNum: e.target.value
        })
        const c=`全部商品可用\r${ConditionType==='a'?'无使用门槛':'订单满'+`${e.target.value}`+'元'}\r${WaiverAmountNum&&'减免'+`${WaiverAmountNum+'元'}`}\r${dateString[0]&&'有效时限:'+ `${dateString[0]}`+ '~'+`${dateString[1]}`}`;
        const cc=`全部商品可用\\r${ConditionType==='a'?'无使用门槛':'订单满'+`${e.target.value}`+'元'}\\r${WaiverAmountNum&&'减免'+`${WaiverAmountNum+'元'}`}\\r${dateString[0]&&'有效时限:'+ `${dateString[0]}`+ '~'+`${dateString[1]}`}`;
        this.setState({
            Description: cc
        })
        this.props.form.setFieldsValue({
            Description: c,
        })
    }

    // 说明
    textChange =(e) => {
        this.setState({
            textName: e.target.value
        })
    }

    // 优惠面额
    onChangeWaiverAmount =(e) => {
        const {ConditionType,ConditionNum, dateString} = this.state;
        this.setState({
            WaiverAmountNum: e.target.value
        })
        const a = `全部商品可用\r${ConditionType==='a'?'无使用门槛':'订单满'+`${ConditionNum}`+'元'}\r${e.target.value&&'减免'+`${e.target.value+'元'}`}\r${dateString[0]&&'有效时限:'+ `${dateString[0]}`+ '~'+`${dateString[1]}`}`;
        const aa = `全部商品可用\\r${ConditionType==='a'?'无使用门槛':'订单满'+`${ConditionNum}`+'元'}\\r${e.target.value&&'减免'+`${e.target.value+'元'}`}\\r${dateString[0]&&'有效时限:'+ `${dateString[0]}`+ '~'+`${dateString[1]}`}`;
        this.setState({
            Description: aa
        })
        this.props.form.setFieldsValue({
            Description: a,
        })
    }

    //
    changeDates =(date, dateStrings) => {
        const {ConditionType,ConditionNum, WaiverAmountNum} = this.state;
        this.setState({
            dateString: dateStrings
        })
        const b = `全部商品可用\r${ConditionType==='a'?'无使用门槛':'订单满'+`${ConditionNum}`+'元'}\r${WaiverAmountNum&&'减免'+`${WaiverAmountNum+'元'}`}\r${dateStrings[0]&&'有效时限:'+ `${dateStrings[0]}`+ '~'+`${dateStrings[1]}`}`;
        const bb = `全部商品可用\\r${ConditionType==='a'?'无使用门槛':'订单满'+`${ConditionNum}`+'元'}\\r${WaiverAmountNum&&'减免'+`${WaiverAmountNum+'元'}`}\\r${dateStrings[0]&&'有效时限:'+ `${dateStrings[0]}`+ '~'+`${dateStrings[1]}`}`;
        this.setState({
            Description: bb
        })
        this.props.form.setFieldsValue({
            Description: b,
        })
    }

    validator = (rule, value, callback) => {
        const form = this.props.form;
        if(value && value !== form.getFieldValue('Condition')) {
            callback('此项为必填项');
        } else {
            callback()
        }
    }

    validator2 = (rule, value, callback) => {
        const form = this.props.form;
        if(value && value !== form.getFieldValue('LimitCount')) {
            callback('此项为必填项');
        } else {
            callback()
        }
    }

    render() {
        const {oemInfo, loading} = this.props;
        const { getFieldDecorator, getFieldValue} = this.props.form;
        const {LimitCountValue, name, ConditionType, ConditionNum,
            WaiverAmountNum, dateString, textName, radio1, radio2,ConditionDesable,LimitCountDesable
        } = this.state;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: { span: 11 },
        };
        const formItemLayout2 = {
            labelCol: {span: 6},
            wrapperCol: { span: 16 },
        };
        return (
            <Form className={styles.contentBox} onSubmit={this.handleSubmit}>
                    <Card bordered={false} className={styles.card}>
                        <Preview
                            title="优惠券"
                            oemInfo={oemInfo}
                            name={name}
                            ConditionType={ConditionType}
                            ConditionNum={ConditionNum}
                            WaiverAmountNum={WaiverAmountNum}
                            dateString={dateString}
                            textName={textName}
                        />
                        <div className={styles.right}>
                            <div className={styles.headText}>基本信息</div>
                            <Form.Item
                                label="优惠券名称"
                                {...formItemLayout}
                            >
                                {getFieldDecorator('Name', {
                                    rules: [{
                                        required: true, message:'此项为必填项',whitespace: true
                                    }],
                                    validateTrigger: 'onBlur'
                                })(
                                    <InputText name="Name" onChange={this.onTextChange} onBlur={this.checkName} showtotal maxLength={10}/>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="发放总量"
                                {...formItemLayout2}
                                extra="修改优惠券总量时只能增加不能减少，请谨慎设置"
                            >
                                {getFieldDecorator('TotalQty', {
                                    rules: [
                                        {pattern: /^1*[1-9]\d{0,4}$/, message: '1~99999之间的数字'},
                                        {required: true, message:'此项为必填项'},
                                    ],
                                })(
                                    <Input addonAfter="张" style={{width: 115}}/>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="适用商品"
                                {...formItemLayout2}
                            >
                                {getFieldDecorator('type')(
                                    <span>全部商品可用</span>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="使用门槛"
                                {...formItemLayout2}
                                className={styles.Redio}
                            >
                                {getFieldDecorator('radio1', {
                                    initialValue: 'a',
                                    rules: [
                                        {required: true, message:'此项为必填项'},
                                    ]
                                })(
                                    <RadioGroup onChange={this.onChangeConditionType}>
                                        <Row>
                                            <Col span={12}>
                                                <Radio value={'a'}>无使用门槛</Radio>
                                            </Col>
                                        </Row>
                                        <Row>
                                            <Col span={8}>
                                                <Radio value={'b'}>订单满</Radio>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item>
                                                    {
                                                    getFieldDecorator('Condition',{
                                                        rules: [
                                                            {required: radio1, message: '此项为必填项'},
                                                            {pattern: /^1*[1-9]\d{0,4}$/, message: '1~99999之间的数字'}
                                                            // {validator: this.validator}
                                                        ]
                                                    })(
                                                    <Input
                                                        addonAfter="元"
                                                        style={{width: 115, marginLeft:8}}
                                                        onChange={this.onChangeCondition}
                                                        disabled={ConditionDesable}
                                                    />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </RadioGroup>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="优惠内容"
                                {...formItemLayout2}
                            >
                                {getFieldDecorator('WaiverAmount', {
                                    rules: [
                                        {required: true, message:'此项为必填项'},
                                        {pattern: /^1*[1-9]\d{0,4}$/, message: '1~99999之间的数字'}
                                    ]
                                })(
                                    <span>
                                        <span>减免</span>
                                        <Input
                                            addonAfter="元"
                                            style={{width: 115, marginLeft:8}}
                                            onChange={this.onChangeWaiverAmount}
                                        />
                                    </span>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="用券时间"
                                {...formItemLayout}
                            >
                                {getFieldDecorator('Date', {
                                    rules: [{required: true, message:'此项为必填项'}]
                                })(
                                    <RangePicker onChange={this.changeDates} />
                                )}
                            </Form.Item>
                            <div className={styles.footText}>领取和使用规则</div>
                            <Form.Item
                                label="每人限领次数"
                                {...formItemLayout2}
                                className={styles.Redio}
                            >
                                {getFieldDecorator('radio2', {
                                    initialValue: 'a',
                                    rules: [
                                        {required: true, message:'此项为必填项'},
                                    ]
                                })(
                                    <RadioGroup onChange={this.onChangeLimitCount}>
                                        <Row>
                                            <Col span={12}>
                                                <Radio value={'a'}>不限次数</Radio>
                                            </Col>
                                        </Row>
                                        <Row>
                                        <Col span={16}>
                                                <Form.Item>
                                                    <Radio value={'b'}>
                                                        {
                                                            getFieldDecorator('LimitCount',{
                                                                rules: [
                                                                    {required: radio2, message: '此项为必填项'},
                                                                    {pattern: /^1*[1-9]\d{0,4}$/, message: '1~99999之间的数字'}
                                                                    // {validator: this.validator2}
                                                                ]
                                                            })(<Input addonAfter="次" style={{width: 115}} disabled={LimitCountDesable}/>)
                                                        }
                                                    </Radio>
                                                </Form.Item>
                                        </Col>
                                        </Row>
                                    </RadioGroup>
                                )}
                            </Form.Item>
                            <Form.Item
                                label="使用说明"
                                {...formItemLayout}
                            >
                                {getFieldDecorator('Description', {
                                    rules: [{required: true, message:'此项为必填项'}]
                                })(
                                    <TextArea
                                        rows={3}
                                        maxLength={300}
                                        onChange={this.textChange}
                                    />
                                )}
                            </Form.Item>
                        </div>
                    </Card>

                    <div className="xkd-bottom-actions">
                            <Button
                                htmlType="submit"
                                type="primary"
                                loading={loading}
                            >
                            保存
                        </Button>
                    </div>
            </Form>
        )
    }
}

export default Form.create()(ReleaseCards);
